package net.enantena.finappsparty2012;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends Activity implements OnClickListener {

	Button nextButton;
	EditText usuari;
	EditText password;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		usuari = (EditText) findViewById(R.id.editText1);
		password = (EditText) findViewById(R.id.editText2);
		nextButton = (Button) findViewById(R.id.button1);
		nextButton.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.button1:
			try {
				HttpURLConnection c = (HttpURLConnection) new URL(Data.loginUser)
						.openConnection();
				c.setUseCaches(false);
				c.setRequestProperty(
						"Authorization",
						"basic "
								+ Base64.encode((usuari.getText() + ":" + password
										.getText()).getBytes(), Base64.NO_WRAP));
				c.connect();

				String response = c.getResponseMessage();

				if (response.contains("Unauthorized")) {
					Toast.makeText(this, "Correct User", Toast.LENGTH_LONG).show();
					
					// FIXME:
					Intent intent = new Intent(Login.this, CreateEvent.class);
					startActivity(intent);
				} else {
					MyApp.setToken(new JSONObject(response).getString("token"));
					Toast.makeText(this, "Correct User", Toast.LENGTH_LONG).show();
					Intent intent = new Intent(Login.this, CreateEvent.class);
					startActivity(intent);
				}

				Log.e("login", response);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		default:
			break;
		}
	}
}
